/**
 * 新增修改完成调用 modalFormOk方法 编辑弹框组件ref定义为modalForm
 * 高级查询按钮调用 superQuery方法  高级查询组件ref定义为superQueryModal
 * data中url定义 list为查询列表  delete为删除单条记录  deleteBatch为批量删除
 */
import { filterObj } from '@/utils/util'
import { deleteAction, getAction, downFile, postAction } from '@/api/manage'
import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { handleExportXls } from '@/utils/util'

export const JeecgListMixin = {
  data() {
    return {
      //token header
      tokenHeader: {
        'X-Access-Token': Vue.ls.get(ACCESS_TOKEN)
      },
      /* 查询条件-请不要在queryParam中声明非字符串值的属性 */
      queryParam: {},
      /* 数据源 */
      dataSource: [],
      /* 分页参数 */
      ipagination: {
        current: 1,
        pageSize: 30,
        pageSizeOptions: ['30', '60', '90'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      /* 排序参数 */
      isorter: {
        column: 'createTime',
        order: 'desc'
      },
      /* 筛选参数 */
      filters: {},
      /* table加载状态 */
      loading: false,
      /* table选中keys*/
      selectedRowKeys: [],
      /* table选中records*/
      selectionRows: [],
      /* 查询折叠 */
      toggleSearchStatus: false,
      /* 高级查询条件生效状态 */
      superQueryFlag: false,
      /* 高级查询条件 */
      superQueryParams: '',
      visible: false,
      backReason: '',
      showBackReasonTip: false,
      backId: '', //点击退回所选的数据id
      emailVisible: false,//工时提交发邮件蒙版
      isCreatedLoadData: true,//标识页面载入的时候，走到created（）生命周期时，是否走loadData()方法加载数据，用于弹出页引入JeecgListMixin提前调接口
    }
  },
  created() {
    if (!this.isCreatedLoadData) {
      return
    }
    //添加beforeLoad方法，方便某些页面在调取list接口前做一些操作
    this.beforeLoad();
    this.loadData();
    //初始化字典配置 在自己页面定义
    this.initDictConfig()
  },
  methods: {
    beforeLoad() {
      // console.log("--这是一个假的方法!")
    },
    initColumns() {
      // console.log(this.defColumns)
      var key = this.$route.name + ':colsettings'
      let colSettings = Vue.ls.get(key)
      if (colSettings == null || colSettings == undefined) {
        let allSettingColumns = []
        this.defColumns.forEach(function (item, i, array) {
          allSettingColumns.push(item.dataIndex)
        })
        this.settingColumns = allSettingColumns
        this.columns = this.defColumns
      } else {
        this.settingColumns = colSettings
        const cols = this.defColumns.filter((item) => {
          if (item.key == 'rowIndex' || item.dataIndex == 'action') {
            return true
          }
          if (colSettings.includes(item.dataIndex)) {
            return true
          }
          return false
        })
        this.columns = cols
      }
    },
    //列设置更改事件
    onColSettingsChange(checkedValues) {
      var key = this.$route.name + ':colsettings'
      Vue.ls.set(key, checkedValues, 7 * 24 * 60 * 60 * 1000)
      this.settingColumns = checkedValues
      const cols = this.defColumns.filter((item) => {
        if (item.key == 'rowIndex' || item.dataIndex == 'action') {
          return true
        }
        if (this.settingColumns.includes(item.dataIndex)) {
          return true
        }
        return false
      })
      this.columns = cols
    },
    loadData(arg) {
      if (!this.url.list) {
        this.$message.error('请设置url.list属性!')
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      var params = this.getQueryParams(); //查询条件
      this.loading = true;
      getAction(this.url.list, params).then((res) => {
        if (res.success) {
          this.dataSource = res.result.records || res.result;
          this.ipagination.total = res.result.total
          if (this.defColumns) {
            this.initColumns()
          } else {
          }
        }
        this.loading = false
      })
    },
    initDictConfig() {
      // console.log("--这是一个假的方法!")
    },
    handleSuperQuery(arg) {
      //高级查询方法
      if (!arg) {
        this.superQueryParams = ''
        this.superQueryFlag = false
      } else {
        this.superQueryFlag = true
        this.superQueryParams = JSON.stringify(arg)
      }
      this.loadData()
    },
    getQueryParams() {
      //获取查询条件
      let sqp = {}
      if (this.superQueryParams) {
        sqp['superQueryParams'] = encodeURI(this.superQueryParams)
      }
      var param = Object.assign(sqp, this.queryParam, this.isorter, this.filters)
      param.field = this.getQueryField()
      param.pageNo = this.ipagination.current
      param.pageSize = this.ipagination.pageSize
      return filterObj(param)
    },
    getQueryField() {
      //TODO 字段权限控制
      var str = 'id,'
      if (this.columns) {
        this.columns.forEach(function (value) {
          // console.log(value)
          str += ',' + value.dataIndex
        })
      }
      return str
    },

    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectionRows
    },
    onClearSelected() {
      this.selectedRowKeys = []
      this.selectionRows = []
    },
    searchQuery() {
      if (this.scrollPage > 1) {
        this.scrollPage = 0
      }
      this.onClearSelected()
      this.loadData(1)
    },
    superQuery() {
      this.$refs.superQueryModal.show()
    },
    searchReset() {
      this.onClearSelected()
      this.queryParam = {}
      this.loadData(1)
    },
    //批量提交
    handleCommit: function () {
      if (!this.url.commitBatch) {
        this.$message.error('请设置url.commitBatch属性!')
        return false
      }
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录！')
        return false
      } else {
        var ids = ''
        for (var a = 0; a < this.selectedRowKeys.length; a++) {
          ids += this.selectedRowKeys[a] + ','
          if (a == this.selectedRowKeys.length - 1) {
            // console.log("selectedIds："+ids)
            var that = this
            that.$confirm({
              title: '确认提交',
              content: '是否提交选中数据?',
              onOk: function () {
                that.$refs.shades.showShade()
                getAction(that.url.commitBatch, {
                  ids: ids
                }).then((res) => {
                  if (res.success) {
                    that.$refs.shades.closeShade()
                    that.$message.success(res.message)
                    that.loadData()
                    that.onClearSelected()
                  } else {
                    that.$refs.shades.closeShade()
                    that.$message.warning(res.message)
                  }
                })
              }
            })
          }
        }

      }
    },
    //批量通过
    handlePass: function () {
      if (!this.url.passBatch) {
        this.$message.error('请设置url.passBatch!')
        return
      }
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录！')
        return
      }
      var errorText = ''
      var ids = ''
      for (var a = 0; a < this.selectedRowKeys.length; a++) {
        if (this.selectionRows[a].taskState != 1) {
          errorText = '请选择待审批数据'
          break
        }
      }
      if (errorText != '') {
        this.$message.error(errorText)
      } else if (a == this.selectedRowKeys.length) {
        for (var b = 0; b < this.selectedRowKeys.length; b++) {
          ids += this.selectedRowKeys[b] + ','
          if (b == this.selectedRowKeys.length - 1) {
            // console.log("selectedIds："+ids)
            var that = this
            that.$confirm({
              title: '确认提交',
              content: '是否提交选中数据?',
              onOk: function () {
                that.$refs.shades.showShade()
                getAction(that.url.passBatch, {
                  ids: ids
                }).then((res) => {
                  if (res.success) {
                    that.$message.success(res.message)
                    that.loadData()
                    that.onClearSelected()
                    that.$refs.shades.closeShade()
                  } else {
                    that.$message.warning(res.message)
                    that.$refs.shades.closeShade()
                  }
                })
              }
            })
          }
        }
      }
    },
    //批量退回
    handleBack: function () {
      if (!this.url.backBatch) {
        this.$message.error('请设置url.backBatch!')
        return
      }
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录！')
        return
      }
      var errorText = '';
      var ids = ''
      for (var a = 0; a < this.selectedRowKeys.length; a++) {
        if (this.selectionRows[a].taskState != 1) {
          errorText = '请选择待审批数据！'
          break
        }
      }
      if (errorText != '') {
        this.$message.error(errorText)
      } else if (a == this.selectedRowKeys.length) {
        for (var b = 0; b < this.selectedRowKeys.length; b++) {
          ids += this.selectedRowKeys[b] + ','
          if (b == this.selectedRowKeys.length - 1) {
            this.backId = ids
            this.visible = true
          }
        }
      }
    },
    //退回原因填写,如果退回原因不为空就执行退回操作
    hideModal() {
      if (this.backReason == '') {
        this.showBackReasonTip = true
      } else {
        this.showBackReasonTip = false
        this.visible = false
        var that = this
        var param = {
          ids: that.backId,
          reason: that.backReason
        }
        that.$confirm({
          title: '确认提交',
          content: '是否提交选中数据?',
          onOk: function () {
            that.backReason = ''
            that.backId = ''
            that.$refs.shades.showShade()
            getAction(that.url.backBatch, param).then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.loadData()
                that.onClearSelected()
                that.$refs.shades.closeShade()
              } else {
                that.$message.warning(res.message)
                that.$refs.shades.closeShade()
              }
            })
          },
          onCancel: function () {
            that.backReason = ''
            that.backId = ''
            that.showBackReasonTip = false
          }
        })
      }
    },
    //批量删除
    batchDel: function () {
      if (!this.url.deleteBatch) {
        this.$message.error('请设置url.deleteBatch属性!')
        return
      }
      if (this.selectedRowKeys.length <= 0) {
        this.$message.warning('请选择一条记录！')
        return
      } else {
        var ids = ''
        for (var a = 0; a < this.selectedRowKeys.length; a++) {
          ids += this.selectedRowKeys[a] + ','
        }
        var that = this
        this.$confirm({
          title: '确认删除',
          content: '是否删除选中数据?',
          onOk: function () {
            deleteAction(that.url.deleteBatch, {
              ids: ids
            }).then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.loadData()
                that.onClearSelected()
              } else {
                that.$message.warning(res.message)
              }
            })
          }
        })
      }
    },
    handleDelete: function (id) {
      if (!this.url.delete) {
        this.$message.error('请设置url.delete属性!')
        return
      }
      var that = this
      deleteAction(that.url.delete, {
        id: id
      }).then((res) => {
        if (res.success) {
          that.$message.success(res.message)
          that.loadData()
          that.onClearSelected()
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    handleEdit: function (record) {
      this.$refs.modalForm.title = '编辑'
      this.$refs.modalForm.edit(record)
    },

    cancelModal() {
      this.visible = false
      this.backReason = ''
      this.backId = ''
      this.showBackReasonTip = false
    },
    handleAdd: function () {
      this.$refs.modalForm.title = '新增'
      this.$refs.modalForm.add()
    },
    handleTableChange(pagination, filters, sorter) {
      if (isNaN(pagination.pageSize)) {
        pagination.pageSize = Number(pagination.pageSizeOptions[0])
      }
      //分页、排序、筛选变化时触发
      //TODO 筛选
      if (Object.keys(sorter).length > 0) {
        this.isorter.column = sorter.field
        this.isorter.order = 'ascend' == sorter.order ? 'asc' : 'desc'
      }
      this.ipagination = pagination
      this.loadData()
    },
    handleToggleSearch() {
      this.toggleSearchStatus = !this.toggleSearchStatus
    },
    modalFormOk() {
      // 新增/修改 成功时，重载列表
      if (this.scrollPage > 1) {
        this.scrollPage = 1
      }
      this.loadData();
      this.onClearSelected()
    },
    handleDetail: function (record) {
      this.$refs.modalForm.title = '详情'
      this.$refs.modalForm.disableSubmit = true
      this.$refs.modalForm.edit(record)
    },
    /* 导出 */
    handleExportXls2() {
      let paramsStr = encodeURI(JSON.stringify(this.getQueryParams()))
      let url = `${window._CONFIG['domianURL']}/${this.url.exportXlsUrl}?paramsStr=${paramsStr}`
      window.location.href = url
    },
    handleExportXls,
    //导出txt
    handleExportTxt() {
      this.$refs.shades.showShade()
      var fileName = ''
      var ids = ''
      //获取导出文件名
      for (var i = 0; i < this.selectedRowKeys.length; i++) {
        ids += '\'' + this.selectedRowKeys[i] + '\','
      }
      var param = {
        departName: this.queryParam.departName ? this.queryParam.departName : '',
        years: this.queryParam.years ? this.queryParam.years : '',
        userName: this.queryParam.userName ? this.queryParam.userName : '',
        ids: ids
      }
      getAction(this.url.exportTxtFileName, param).then((res) => {
        fileName = res.fileName
        if (fileName != '') {
          downFile(this.url.exportTxtUrl, param).then((data) => {
            if (!data) {
              this.$message.warning('文件下载失败')
              return
            }
            if (typeof window.navigator.msSaveBlob !== 'undefined') {
              console.log(this.url.exportTxtUrl == '/reimbursement/reimbursement/exportTxt')
              if (this.url.exportTxtUrl == '/reimbursement/reimbursement/exportTxt') {
                window.navigator.msSaveBlob(new Blob([data]), fileName + '.gbpt')
              } else {
                window.navigator.msSaveBlob(new Blob([data]), fileName + '.txt')
              }
            } else {
              let url = window.URL.createObjectURL(new Blob([data]))
              let link = document.createElement('a')
              link.style.display = 'none'
              link.href = url
              if (this.url.exportTxtUrl == '/reimbursement/reimbursement/exportTxt') {
                link.setAttribute('download', fileName + '.gbpt')
              } else {
                link.setAttribute('download', fileName + '.txt')
              }
              document.body.appendChild(link)
              link.click()
              document.body.removeChild(link) //下载完成移除元素
              window.URL.revokeObjectURL(url) //释放掉blob对象
              this.onClearSelected()
              this.$refs.shades.closeShade()
            }
          })
        }
      })
    },
    /* 导入 */
    handleImportExcel(info) {
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList)
      }
      if (info.file.status === 'done') {
        if (info.file.response.success) {
          this.$message.success(`${info.file.name} 文件上传成功`)
          this.loadData()
        } else {
          this.$message.error(`${info.file.name} ${info.file.response.message}.`)
        }
      } else if (info.file.status === 'error') {
        this.$message.error(`文件上传失败: ${info.file.msg} `)
      }
    },
    /* 图片预览 */
    getImgView(text) {
      if (text && text.indexOf(',') > 0) {
        text = text.substring(0, text.indexOf(','))
      }
      return window._CONFIG['imgDomainURL'] + '/' + text
    },
    /* 文件下载 */
    uploadFile(text) {
      if (!text) {
        this.$message.warning('未知的文件')
        return
      }
      if (text.indexOf(',') > 0) {
        text = text.substring(0, text.indexOf(','))
      }
      window.open(window._CONFIG['domianURL'] + '/sys/common/download/' + text)
    },
    openFileModal(record) {
      this.$refs.TaskFileModal.open(record)
    },
    handleProcessRecords(record) {
      this.$refs.ProcessRecordModal.open(record)
    },
  }

}